package com.ias.agdis_r.db.message;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ias.agdis_r.util.MyMessage;
import com.ias.agdis_r.util.S;

/**
 * 
 * @author qibo.yu
 * @version 2015年8月20日 下午4:17:32
 **/
public class MessageUtil {

	private static final Map<String, Method> methodCache = new HashMap<String, Method>();
	private static final Map<String, Pattern> patternCache = new HashMap<String, Pattern>();

	/**
	 * 将网关发送下来的短语解析为MessageBean对象
	 * 
	 * @param message
	 * @return
	 */
	public static MyMessageBean analysesMessage(String message) {

		if (methodCache.size() == 0) {
			initCache();
		}

		MyMessageBean bean = new MyMessageBean();

		for (String name : methodCache.keySet()) {
			Matcher matcher = patternCache.get(name).matcher(message);
			if (matcher.find()) {
				String str = matcher.group(0);
				String value = str.substring(name.length(), str.length() - 1);
				if (S.isNotEmpty(value)) {
					try {
						methodCache.get(name).invoke(bean, value);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

		bean.setTXT(MyMessage.getTxtContent(message));

		return bean;

	}

	private static void initCache() {
		for (Method method : MyMessageBean.class.getMethods()) {
			String name = method.getName();
			if (name.startsWith("set")) {
				String key = name.substring(3);
				methodCache.put(key, method);
				patternCache.put(key, Pattern.compile(key + "[^,]*,"));
			}
		}
	}

}
